package Server;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.LinkedList;

import static Server.Server.*;

public class SocketThread extends Thread {
    public Socket s;
    public User user;


    public SocketThread(Socket s) {
        this.s = s;
        user = new User();
    }

    @Override
    public void run() {
        while (true) {
            try {
                initStreams();
                if (login()) {
                    break;
                }
            } catch (IOException | ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
        }
        
        // 若用户数量小于 2 则等待
        while (users.size() < MAXPLAYER) {
            try {
                System.out.println("当前用户人数: " + users.size());

                sleep(1000);

            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        preGame();
        try {
            startGame();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public void initGame() throws IOException {
        ArrayList<Object> command = new ArrayList<>();
        command.add(user.getStatus());
        if(user.getStatus().equals("DRAW"))
            command.add(Util.getSubject());
        user.oos.writeObject(command);
        System.out.println("已向客户端发送状态信息");
        System.out.println(currentThread().getName() + ": 当前用户:" + users.get(s).getUserName());
        System.out.println(currentThread().getName() + ": 当前用户状态:" + users.get(s).getStatus());
    }

    public void preGame() {
        try {
            if (user.buf.readLine().equals("准备开始游戏")) {
                user.pw.println("2");
            }
            if (currentThread().getName().equals("Thread-1")) {
                users.get(s).setStatus("DRAW");
            } else {
                users.get(s).setStatus("GUESS");
            }

            if (user.buf.readLine().equals("开启游戏")) {
                initGame();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void startGame() throws IOException, ClassNotFoundException {
        System.out.println(user.getUserName() + user.getStatus());
        if (user.getStatus().equals("DRAW")) {
            ArrayList<Object> command;
            while ((command = (ArrayList<Object>) user.ois.readObject())!= null && !s.isClosed()) {
                // 若收到客户端发来的绘制请求，接受数据并转发
                String code = (String) command.get(0);
                System.out.println(code);
                if (code.equals("绘制")) {
                    commandDraw(command);
                }
            }
        }
        else{
            ArrayList<Object> command;
            while ((command = (ArrayList<Object>) user.ois.readObject())!= null && !s.isClosed()) {
                // 若收到客户端发来的绘制请求，接受数据并转发
                String code = (String) command.get(0);
                System.out.println(code);
                if (code.equals("提交答案")) {
                    commandSubmit(command);
                }
            }
        }
        System.out.println("有人下线");
        this.interrupt();
    }

    public void commandDraw(ArrayList<Object> command) throws IOException, ClassNotFoundException {
        System.out.println("接收到绘制请求");
        users.forEach((k, v) -> {
            try {
                if (!(v == user)) {
                    // 发送绘制指令，准备接受数据
                    System.out.println("准备向" + k.getInetAddress().getHostName() + "发送数据");
                    v.oos.writeObject(command);
                    System.out.println("发送完成");
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    public void commandSubmit(ArrayList<Object> command){
        String ans = (String) command.get(1);
        if(ans.equals(Util.nowSubject)){
            ArrayList<Object> res = new ArrayList<>();
            res.add("提交答案");
            res.add(true);
            users.forEach((k, v) -> {
                try {
                    v.oos.writeObject(res);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }

    public boolean login() throws IOException, ClassNotFoundException {
        LinkedList<String> userAccount;

        userAccount = (LinkedList<String>) user.ois.readObject();
        String account = userAccount.get(0);
        String passWd = userAccount.get(1);

        for(String key : info.keySet()){
            if(account.equals(key) && passWd.equals(info.get(key))){
                user.oos.writeObject("true");
                user.setUserName(account);
                users.put(Server.temp, user);
                return true;
            }
        }

        user.oos.writeObject("false");
        return false;
    }

    private void initStreams() throws IOException {
        user.buf = new BufferedReader(new InputStreamReader(s.getInputStream()));
        user.pw = new PrintWriter(s.getOutputStream(), true);
        user.ois = new ObjectInputStream(s.getInputStream());
        user.oos = new ObjectOutputStream(s.getOutputStream());
    }
}